import { Message, Dialog } from '@alifd/next';
import {
  showReloginAlert,
  handlerServiceError,
} from '@src/common/GlobalValue';
import { store, history } from '../index';

import axios from 'axios';

export async function request(url, options) {
  const newOptions = { ...options };
  newOptions.headers = {
    Accept: 'application/json',
    'Content-Type': 'application/json;charset=utf-8',
    ...newOptions.headers,
  };
  let _params = {},
    _data = {};
  if (newOptions.method === 'post' || newOptions.method === 'put') {
    if (newOptions.body) {
      Object.keys(newOptions.body).forEach(key => _data[key] = newOptions.body[key]);
      // console.log('_data===',_data)
      newOptions.data = { ..._data };
    }
  } else if (newOptions.method === 'get' || newOptions.method === 'delete') {
    if (newOptions.body) {
      Object.keys(newOptions.body).forEach(key => _params[key] = newOptions.body[key]);
      // console.log('_params===',_params)
      newOptions.params = { ..._params };
    }
  }
  delete newOptions.body;
  // console.log('newOptions===',newOptions);
  return await axios(url, newOptions)
    .then((response) => {
      if (response.status == "200") {
        return response.data
      }
      throw new Error('网络错误')

    })
    .then((model) => {
      return model;
    }).catch((error) => {
      if (error.message) {
        Message.show({
          type: 'error',
          title: '错误',
          content: error.message,
        });
      }
      throw error;
    });
}

// 添加请求拦截器
axios.interceptors.request.use((config) => {
  console.log('config===', config)
  //判断是否登录
  return new Promise((resolve, reject) => {
    const state = store.getState();
    const userInfo = state.tokenReducer.userInfo;
    if (state.route.location.pathname == "/user/login" || userInfo) {
      resolve(Object.assign({}, userInfo, config));
      return;
    }
    reject();
    //需要用户登录
    showReloginAlert();
  })
}, (error) => {
  // 对请求错误做些什么
  return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use((response) => {
  console.log('response===', response)
  // 对响应数据做点什么
  if (!response.data.success) {
    return handlerServiceError(response.data)
  }
  return response;
}, (error) => {
  // 对响应错误做点什么
  return Promise.reject(error);
});

export async function fetchDataWithGet(url, params, toast = true) {
  const header = {
    'Content-Type': 'application/json;charset=UTF-8',
  };

  // 以json字符串格式提交
  const bodyParams = {};
  for (const key in params) {
    bodyParams[key] = params[key];
  }

  // send get request
  const requestUrl = url;
  const fetchPromise = axios(requestUrl, {
    method: 'get',
    params: bodyParams,
    headers: header,
  }).then((response) => {
    if (response.status == "200") {
      return response.data
    }
    throw new Error('网络错误')

  }).then((model) => {
    if (model.success) {
      return model
    }

    return handlerServiceError(model)

  }).then((model) => {
    if (model && model.isRetry) {
      return fetchDataWithGet(url, { ...params });
    }
    return model;
  })
    .catch((error) => {
      if (toast && error.message) {
        Message.show({
          type: 'error',
          title: '错误',
          content: error.message,
        });
      }
      throw error;
    });

  return await fetchPromise;
}

export async function fetchDataWithPost(url, params, toast = true) {
  const header = {
    'Content-Type': 'application/json;charset=UTF-8',
  };

  // 以json字符串格式提交
  const bodyParams = {};
  for (const key in params) {
    bodyParams[key] = params[key];
  }

  // send post request
  const requestUrl = url;
  const fetchPromise = axios(requestUrl, {
    method: 'post',
    data: bodyParams,
    headers: header,
  }).then((response) => {
    if (response.status == "200") {
      return response.data
    }
    throw new Error('网络错误')

  }).then((model) => {
    if (model.success) {
      return model
    }

    return handlerServiceError(model)

  }).catch((error) => {
    if (toast && error.message) {
      Message.show({
        type: 'error',
        title: '错误',
        content: error.message,
      });
    }
    throw error;
  });

  return await fetchPromise;
}

export async function fetchDataWithDelete(url, params, toast = true) {
  const header = {
    'Content-Type': 'application/json;charset=UTF-8',
  };

  // 以json字符串格式提交
  const bodyParams = {};
  for (const key in params) {
    bodyParams[key] = params[key];
  }

  // send post request
  const requestUrl = url;
  const fetchPromise = axios(requestUrl, {
    method: 'delete',
    params: bodyParams,
    headers: header,
  }).then((response) => {
    if (response.status == "200") {
      return response.data
    }
    throw new Error('网络错误')

  }).then((model) => {
    if (model.success) {
      return model
    }

    return handlerServiceError(model)

  }).catch((error) => {
    if (toast && error.message) {
      Message.show({
        type: 'error',
        title: '错误',
        content: error.message,
      });
    }
    throw error;
  });

  return await fetchPromise;
}
